package chapter8.eg10.netty;

import chapter8.eg10.SubscribeReqProto;
import chapter8.eg10.SubscribeReqProto.SubscribeReq;
import chapter8.eg10.SubscribeRespProto;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@Sharable
public class SubReqServerHandler extends SimpleChannelInboundHandler<SubscribeReqProto.SubscribeReq> {

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, SubscribeReq req) throws Exception {
    if ("Lilinfeng".equalsIgnoreCase(req.getUserName())) {
      System.out.println("Server accept client subscribe req: [" + req.toString() + "]");
      ctx.writeAndFlush(resp(req.getSubReqID()));
    }
  }

  private SubscribeRespProto.SubscribeResp resp(int subReqID) {
    SubscribeRespProto.SubscribeResp.Builder builder =
      SubscribeRespProto.SubscribeResp.newBuilder()
        .setSubReqID(subReqID)
        .setRespCode(0)
        .setDesc("Netty book order succeed, 3 days later, sent to the designated address");
    return builder.build();
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
